
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList
var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent

export class ListenUtils {

  constructor(onresult) {
    var grammar = '*'

    this.recognition = new SpeechRecognition();
    this.speechRecognitionList = new SpeechGrammarList();
    this.speechRecognitionList.addFromString(grammar, 1);
    this.recognition.grammars = this.speechRecognitionList;
    this.recognition.continuous = false;
    this.recognition.lang = 'zh-Hans';
    this.recognition.interimResults = false;
    this.recognition.maxAlternatives = 1;
    // onresult
    this.recognition.onresult = function (event) {
      // var res = event.results[0][0].transcript;
      onresult(event)
    }

    this.state = false
  }

  start() {
    if(this.state) {
      this.recognition.abort()
    }
    this.recognition.start();
    this.state = true
    console.log('Ready to receive a color command.');
  }

  stop() {
    if(this.state) {
      this.recognition.stop()
      console.log('Stopping!');
      this.state = false
    }
  }

}